#include <QtGui>

#include "renderarea.h"
#include "mandelbrotthread.h"
#include "mandelbrotwindow.h"
#include "juliawindow.h"

MandelbrotWindow::MandelbrotWindow(JuliaWindow *julia, QWidget *parent)
    : QWidget(parent), juliaWindow(0)
{
    renderArea = new RenderArea(new MandelbrotThread(this));

    iterationSpinBox = new QSpinBox;
    iterationSpinBox->setRange(0, 1000);

    iterationLabel = new QLabel(tr("&Iterations:"));
    iterationLabel->setBuddy(iterationSpinBox);

    helpLabel = new QLabel("Use mouse wheel or the '+' and '-' keys to zoom.\n"
                           "Press and hold left mouse button to scroll.\n"
                           "Press right mouse button to select Julia coefficient.");

    resetButton = new QPushButton(tr("&Reset"));
    quitButton = new QPushButton(tr("&Quit"));

    connect(iterationSpinBox, SIGNAL(valueChanged(int)),
            renderArea, SLOT(setIteration(int)));
    connect(resetButton, SIGNAL(clicked()),
            renderArea, SLOT(reset()));
    connect(quitButton, SIGNAL(clicked()),
            qApp, SLOT(quit()));

    QHBoxLayout *topLayout = new QHBoxLayout;
    topLayout->addWidget(iterationLabel);
    topLayout->addWidget(iterationSpinBox);
    topLayout->addStretch();
    
    QHBoxLayout *bottomLayout = new QHBoxLayout;
    bottomLayout->addWidget(helpLabel, 1);
    bottomLayout->addWidget(resetButton);
    bottomLayout->addWidget(quitButton);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(topLayout);
    mainLayout->addSpacing(6);
    mainLayout->addWidget(renderArea);
    mainLayout->addSpacing(6);
    mainLayout->addLayout(bottomLayout);

    setLayout(mainLayout);

    iterationSpinBox->setValue(20);

    setWindowTitle(tr("Mandelbrot"));
    setJuliaWindow(julia);
}

void MandelbrotWindow::setJuliaWindow(JuliaWindow *julia)
{
    if (julia)
        connect(renderArea, SIGNAL(positionChanged(double,double)),
                julia, SLOT(setLambda(double,double)));
    else if (juliaWindow)
        disconnect(renderArea, SIGNAL(positionChanged(double,double)),
                   juliaWindow, SLOT(setLambda(double,double)));
    juliaWindow = julia;
}
